package com.mbmall.ware.service.impl;

import com.common.constant.WareConstant;
import com.mbmall.ware.entity.PurchaseDetailEntity;
import com.mbmall.ware.service.PurchaseDetailService;
import com.mbmall.ware.service.WareSkuService;
import com.mbmall.ware.vo.MergeVo;
import com.mbmall.ware.vo.PurchaseDoneVo;
import com.mbmall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.mbmall.ware.dao.PurchaseDao;
import com.mbmall.ware.entity.PurchaseEntity;
import com.mbmall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {


        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo vo) {
        Long purchaseId=vo.getPurchaseId();
        if(purchaseId==null){

            PurchaseEntity purchaseEntity=  new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId=purchaseEntity.getId();

        }


        List<Long> items= vo.getItems();
        Long finalPurchaseId=purchaseId;
        List<PurchaseDetailEntity> collect = items.stream().map((item) -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).filter(i->{
            //状态为o或1才可以进行合并
            if(i.getStatus()==WareConstant.PurchaseDetailEnum.CREATED.getCode()
                    ||i.getStatus()==WareConstant.PurchaseDetailEnum.ASSIGNED.getCode()){
                return true;
            }
            return false;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(collect);
        PurchaseEntity entity = new PurchaseEntity();
        entity.setUpdateTime(new Date());
        entity.setId(finalPurchaseId);
        this.updateById(entity);
    }

    /**
     * 领取采购单
     * @param ids
     */
    @Override
    public void received(List<Long> ids) {
        //确认当前采购单是新建或已分配状态

        List<PurchaseEntity> collect = ids.stream().map((id) -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter((p) -> {
            if (p.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || p.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map((item) -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //改变采购单状态
        this.updateBatchById(collect);

        //改变采购项状态
        collect.forEach((item)->{
            List<PurchaseDetailEntity> entities=purchaseDetailService.listDetailByPurchase(item.getId());
            List<PurchaseDetailEntity> finalEntities = entities.stream().map((entity) -> {
                PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
                purchaseDetail.setId(entity.getId());
                purchaseDetail.setStatus(WareConstant.PurchaseDetailEnum.BUYING.getCode());
                return purchaseDetail;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(finalEntities);
        });
    }

    /**
     * 完成采购单
     * @param purchaseDoneVo
     */
    @Transactional
    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        //1、改变采购单状态,状态取决于采购项状态的情况，  采购项全完成才是完成
        Long id = purchaseDoneVo.getId();

        //2、改变采购项状态
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        ArrayList<PurchaseDetailEntity> updates=new ArrayList<>();
        Boolean flag=true;
        for (PurchaseItemDoneVo item:
                items) {
            PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
            if (item.getStatus()==WareConstant.PurchaseDetailEnum.HASERROR.getCode()) {
                flag=false;
                purchaseDetail.setStatus(item.getStatus());
            }else {
                purchaseDetail.setStatus(WareConstant.PurchaseDetailEnum.FINISH.getCode());
                //3、将成功采购的进行入库
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());

                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());

            }
            purchaseDetail.setId(item.getItemId());
            updates.add(purchaseDetail);
        }

        purchaseDetailService.updateBatchById(updates);
        //1、改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode()
                : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
        //3、将成功采购的进行入库
    }

}